package cz.apnetis.gwt.client;

import java.util.Iterator;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class TableHeader extends Composite implements HasWidgets {

  private static TableHeaderUiBinder uiBinder = GWT
  .create(TableHeaderUiBinder.class);

  interface TableHeaderUiBinder extends UiBinder<Widget, TableHeader> {
  }

  @UiField
  Label positionLabel;
  @UiField
  ToolButton addButton;
  @UiField
  ToolButton previousButton;
  @UiField
  ToolButton nextButton;
  @UiField
  HorizontalPanel centerPanel;
  /** Table which own this table */
  private final ResultTable<?, ?> resultTable;

  public TableHeader(final ResultTable<?, ?> resutlTable) {
    this.resultTable = resutlTable;

    initWidget(uiBinder.createAndBindUi(this));
  }

  /** Initialize of visibility of buttons etc */
  public final void init() {
    setHasNext(this.resultTable.getTableModel().hasNext());
    setHasPrevious(this.resultTable.getTableModel().hasPrevious());
    if (this.resultTable instanceof ResultTableEditable) {
      this.addButton.setVisible(((ResultTableEditable) this.resultTable).isInsertable());
    }
  }

  public final void setPositionText(final String positionText) {
    this.positionLabel.setText(positionText);
  }

  public final void setHasPrevious(final boolean previous) { this.previousButton.setVisible(previous); }
  public final void setHasNext(final boolean next) { this.nextButton.setVisible(next); }

  @Override
  public void add(final Widget w) {
    this.centerPanel.add(w);
  }

  @Override
  public void clear() {
    this.centerPanel.clear();
  }

  @Override
  public Iterator<Widget> iterator() {
    return this.centerPanel.iterator();
  }

  @Override
  public boolean remove(final Widget w) {
    return this.centerPanel.remove(w);
  }

  @UiHandler("previousButton")
  void onPreviousClick(final ClickEvent e) {
    if (this.resultTable.getTableModel().hasPrevious()) {
      this.resultTable.getTableModel().loadPrevious(this.resultTable);
    }
  }

  @UiHandler("nextButton")
  void onNextClick(final ClickEvent e) {
    if (this.resultTable.getTableModel().hasNext()) {
      this.resultTable.getTableModel().loadNext(this.resultTable);
    }
  }

  @UiHandler("addButton")
  void onAddClick(final ClickEvent e) {
    ((TableModelEditable) this.resultTable.getTableModel()).addRow();
    this.resultTable.paint();
  }
}
